package edu.nf.bs.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import edu.nf.bs.dao.ExpressInfoMapper;
import edu.nf.bs.dao.OrderInfoMapper;
import edu.nf.bs.dao.UserInfoMapper;
import edu.nf.bs.dao.impl.DeliveryManDaoImpl;
import edu.nf.bs.dao.impl.ExpressInfoMapperImpl;
import edu.nf.bs.dao.impl.OrderInfoMapperImpl;
import edu.nf.bs.dao.impl.UserInfoMapperImpl;
import edu.nf.bs.entity.ExpressInfo;
import edu.nf.bs.entity.OrderInfo;
import edu.nf.bs.entity.UserInfo;
import edu.nf.bs.service.ExpressService;
import edu.nf.bs.service.impl.DeliveryServiceImpl;
import edu.nf.bs.service.impl.ExpressServiceImpl;
import edu.nf.bs.service.impl.OrderInfoServiceImpl;
import edu.nf.bs.service.impl.UserInfoServiceImpl;
import edu.nf.bs.util.AlipayConfig;
import edu.nf.bs.util.BaiDuMapUnit;
import edu.nf.bs.util.UUIDUtil;
import edu.nf.bs.vo.AddressVO;
import edu.nf.bs.vo.ResultVO;
import edu.nf.bs.vo.UserAddressVO;
import org.mvc.web.annotation.RequestMapping;
import org.mvc.web.servlet.View;
import org.mvc.web.view.JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ExpressContraller extends BaseContraller {

    @RequestMapping("/express/list")
    public View queryExpress(String expressId, Integer page, Integer limit) {
        ExpressInfoMapper mapper = new ExpressInfoMapperImpl();
        ExpressServiceImpl service = new ExpressServiceImpl();
        service.setExpressInfoMapper(mapper);
        PageInfo<ExpressInfo> expressInfoPageInfo = service.queryExpress(expressId, page, limit);
        ResultVO<List<ExpressInfo>> expressInfo = page(expressInfoPageInfo);
        return new JsonView(expressInfo);
    }

    @RequestMapping("/express/addExpress")
    public View addExpress(ExpressInfo express,HttpServletRequest req, HttpServletResponse resp) {

        ExpressInfoMapper mapper = new ExpressInfoMapperImpl();
        ExpressServiceImpl service = new ExpressServiceImpl();
        service.setExpressInfoMapper(mapper);
        //随机生成快递编号
        Long expressId =UUIDUtil.randomNum();
        //将快递编号转换成String类型
        String expId = Long.toString(expressId);
        //把转换后的id set 到express对象
        express.setExpressId(expId);

        System.out.println(express);
        UserInfoMapper userInfoMapper=new UserInfoMapperImpl();

        UserInfo userByPhone = userInfoMapper.getUserByPhone(express.getUserPhone());

        service.addExpress(express);
        //添加订单
        OrderInfoMapper orderInfoMapper=new OrderInfoMapperImpl();
        OrderInfoServiceImpl orderInfoService=new OrderInfoServiceImpl();
        orderInfoService.setOrderInfoMapper(orderInfoMapper);

        Long order = UUIDUtil.randomNum();
        String orderId = Long.toString(order);
        System.out.println(orderId);
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setOrderId(orderId);
        orderInfo.setExpressId(expId);
        DeliveryManDaoImpl deliveryManDao = new DeliveryManDaoImpl();
        DeliveryServiceImpl deliveryService = new DeliveryServiceImpl();
        deliveryService.setDeliveryManMapper(deliveryManDao);
        List<String> strings = deliveryService.queryDeliveryManId();
        //生成随机数
        Random random = new Random();
        //把查询出来的快递员编号填充到 订单信息表   随机派一个快递员去揽件
        orderInfo.setDeliveryManId(strings.get(random.nextInt(strings.size())));
        orderInfo.setLogisticsId(null);
        if(userByPhone!=null){

            orderInfo.setUserId(userByPhone.getUserId());
        }

        orderInfo.setOrderStatus(1);
        System.out.println(orderInfo);
        orderInfoService.addOrderInfo(orderInfo);
        UserAddressVO geocoderLatitude = BaiDuMapUnit.getGeocoderLatitude(express.getUserAddress());
        UserAddressVO geocoderLatitude1 = BaiDuMapUnit.getGeocoderLatitude(express.getIncomingAddress());
        List<Object> list=new ArrayList<>();
        list.add(expId);
        list.add(geocoderLatitude);
        list.add(geocoderLatitude1);
        ResultVO success = success(list);
        return new JsonView(success);
    }
    @RequestMapping("/address/queryAddress")
    public View queryAddress(String userAddress,String imAddress){
        UserAddressVO geocoderLatitude = BaiDuMapUnit.getGeocoderLatitude(userAddress);
        UserAddressVO geocoderLatitude1 = BaiDuMapUnit.getGeocoderLatitude(imAddress);
        List<Object> list=new ArrayList<>();
        list.add(geocoderLatitude);
        list.add(geocoderLatitude1);
        ResultVO<List<Object>> success = success(list);
        return new JsonView(success);
    }


    @RequestMapping("/express/updateExpress")
    public void updateExpress(HttpServletRequest req,HttpServletResponse resp){
        ExpressInfoMapper mapper = new ExpressInfoMapperImpl();
        ExpressServiceImpl service = new ExpressServiceImpl();
        service.setExpressInfoMapper(mapper);
        System.out.println("---------------------------"+req.getParameter("expressId"));
        Float expressPrice =Float.parseFloat(req.getParameter("expressPrice"));
        service.updateExpress(req.getParameter("expressId"),expressPrice);


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ req.getParameter("expressId") +"\","
                + "\"total_amount\":\""+ expressPrice+"\","
                + "\"subject\":\""+ "百事快递" +"\","
                + "\"body\":\""+ "百事快递" +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = null;
        try {
            resp.setContentType("text/html;charset=utf-8");
            result = alipayClient.pageExecute(alipayRequest).getBody();
            //输出
            PrintWriter out = resp.getWriter();
            out.println(result);

        } catch (AlipayApiException | IOException e) {
            e.printStackTrace();
        }
    }

}
